/*
    SUSAN® - Sole of Unix Save ANything

   

   
*/

#include "watchdog_timer.h"
#include "include/jcr.h"
#include "lib/timer_thread.h"
#include "lib/watchdog.h"

#include <cassert>

static const int debuglevel = 900;

WatchdogTimer::WatchdogTimer(JobControlRecord* jcr)
{
  timer_item = TimerThread::NewTimer();
  timer_item->user_data = this;
  timer_item->single_shot = true;
  jcr_ = jcr;
}

WatchdogTimer::~WatchdogTimer()
{
  if (timer_item) { UnregisterTimer(timer_item); }
}

void WatchdogTimer::Start(std::chrono::milliseconds interval)
{
  timer_item->interval = interval;
  RegisterTimer(timer_item);
}

void WatchdogTimer::Stop()
{
  if (timer_item) {
    UnregisterTimer(timer_item);
    timer_item = nullptr;
  }
}

void BThreadWatchdog::Callback(TimerThread::Timer* item)
{
  BThreadWatchdog* timer = static_cast<BThreadWatchdog*>(item->user_data);
  if (!timer) { return; }

  if (timer->jcr_) {
    Dmsg2(debuglevel, "killed JobId=%u Job=%s\n", timer->jcr_->JobId,
          timer->jcr_->Job);
  }

  pthread_kill(timer->thread_id_, TIMEOUT_SIGNAL);
}

void BThreadWatchdog::Init()
{
  thread_id_ = pthread_self();
  timer_item->user_callback = Callback;
}

BThreadWatchdog::BThreadWatchdog(JobControlRecord* jcr) : WatchdogTimer(jcr)
{
  // has to be started by Start(interval)
  Init();
}

BThreadWatchdog::BThreadWatchdog(std::chrono::milliseconds interval,
                                 JobControlRecord* jcr)
    : WatchdogTimer(jcr)
{
  assert(interval != std::chrono::seconds::zero());

  Init();

  Start(interval);
}
